% Function : cut off section whose gradient is little
% Parameter:
%   data: section data(vector)
%   limt: lower limit of gradient
% Return:
%   r: number of points needed to be delete
function r = cutS(data, limt)
    if nargin < 2
        error('Usage: cutS(data, limt)');
    end

    n    = numel(data); % number of data
    st   = 1;           % start of search scope
    ed   = n;           % end of search scope
    data = sort(data);  % sort data in ascending order

    while true
        % binary search: find rank of average of minimum and maximum
        lo = st;
        hi = ed;
        v  = (data(st) + data(ed)) / 2;
        while lo < hi
            mid = floor((lo + hi) / 2);
            if v > data(mid)
                lo = mid + 1;
            else
                hi = mid;
            end
        end

        % gradient of remaining data
        grad = 60 * (data(n) - data(lo)) / (n - lo);    % centigrade per hour

        % convergence condition
        if lo == ed || lo == st
            r = lo;
            break;
        end

        % update start or end of section
        if grad < limt
            st = lo;
        else
            ed = lo;
        end
    end

    % shrink the scope
    while r > 2 && data(r) - data(r - 1) > 0.1
        r = r - 1;
    end
end
